<script setup lang="ts">
import { onMounted, ref, reactive, onBeforeUnmount, shallowRef,watch,defineModel } from 'vue';
import { Global } from '../Global';
import JmsUploader from "jms-uploader";

const modelValue = defineModel<string>('modelValue');

const uploadingProgress = ref(0);
const uploading = ref(false);
const fileRef = ref(<HTMLInputElement><any>null);



const upload = async () => {
  //自定义请求头
  var headers = function () {
    return { "Authorization": Global.UserInfo.Token };
  };

  //提交的body
  var dataBody = {

  };

  var uploader = new JmsUploader(Global.UploadFileUrl, <any>fileRef.value.files, headers, dataBody);

  uploader.setPartSize(1024 * 300);//设置分块大小，默认是102400

  uploader.onUploading = (percent, uploadedSize, totalSize) => {
    if (percent == 100)
      percent = 99;
    uploadingProgress.value = percent;
  };

  uploadingProgress.value = 0;
  uploading.value = true;
  try {
    var ret = JSON.parse(await uploader.upload());
    //上传完毕
    console.log("上传完毕", ret);
    modelValue.value = ret[0].Url;
  } catch (error) {
    Global.showError(error);
  }
  finally {
    uploading.value = false;
    uploadingProgress.value = 0;
  }
}
</script>
<template>
    <div>
        <el-progress type="circle" :percentage="uploadingProgress" v-if="uploading" />
        <div class="uploadItem" v-else>
            <img :src="modelValue" v-if="modelValue">
            <div class="uploadBorder" v-else>
                <el-icon>
                    <Plus />
                </el-icon>
            </div>
            <input ref="fileRef" type="file" accept=".jpg,.png,jpeg" @change="upload" />
        </div>
    </div>
</template>

<style scoped lang="scss">
.uploadItem {
    position: relative;

    img {
        width: 126px;
        height: 126px;
    }

    input {
        position: absolute;
        cursor: pointer;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        opacity: 0;
    }

    .uploadBorder {
        width: 126px;
        height: 126px;
        font-size: 30px;
        color: #eee;
        border-radius: 5px;
        border: 1px solid #eee;
        display: flex;
        align-items: center;
        justify-content: center;
    }
}
</style>